promise()
is another coroutine builder. It works a lot like async()
, in that
it executes a coroutine and lets you get the result from the lambda expression.
The fundamental difference is that promise()
returns a Promise
, which is a
Kotlin wrapper around the JavaScript Promise
object. This is useful for
interoperability with JavaScript libraries that take a Promise
.
To get the result from a Promise
, you can call then()
and pass a lambda
expression that will be passed the result returned from a coroutine. This is
a bit like calling await()
on a Deferred
object. However, await()
is
a suspend
function, since it is part of the coroutines system. then()
on Promise
is part of JavaScript, and so you do not need to call then()
inside of a coroutine.
Note that promise()
only works on Kotlin/JS, not other Kotlin environments.